import { login, getInfo, getDetailInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    // getToken用于获取本来就已经存在的token
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  UPDATA_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 实现一个action用来登录
  async login ({ commit }, form) {
    // context类似于$store
    // payload是触发action时传递的参数
    try {
      const ret = await login({
        mobile: form.username,
        password: form.password
      })
      console.log(ret)

      if (ret.code === 10000) {
        // 登录成功,先保存到state里面，再缓存token到本地存储
        commit('SET_TOKEN', ret.data)
        setToken(ret.data)
        return Promise.resolve(true)
      } else {
        // 登录失败
        return Promise.reject(false)
      }
    } catch (err) {
      console.log(err)
      return Promise.reject(false)
    }
  },

  // 获取用户信息
  async getInfo ({ commit }) {
    // 获取基本信息
    const userInfo = await getInfo()
    // 根据id获取详细信息
    const twoInfo = await getDetailInfo(userInfo.data.userId)
    // 调用mution给userInfo赋值
    commit('UPDATA_USERINFO', {
      ...userInfo.data,
      ...twoInfo.data
    })
  },

  // user logout
  logout ({ commit }) {
    // 清除token
    commit('SET_TOKEN', '')
    // 清除用户信息
    commit('UPDATA_USERINFO', null)
    // 移除本地token
    removeToken()
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  // 命名空间，把模块变成局部的
  namespaced: true,
  state,
  mutations,
  actions
}
